package com.java.code.proxy;

import lombok.NoArgsConstructor;
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy {
    /**
     * 不用实现类 mybatis实现原理
     */
    @Test
    public void proxy1() {
        Object o = Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[]{Subject.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("方法调用");
                        return null;
                    }
                });
        Subject subject = (Subject) o;
        subject.show();
    }

    /**
     * 实现类
     */
    @Test
    public void proxy2() {
        JavaDynamicProxy proxy = new JavaDynamicProxy();
        Subject subject = (Subject) proxy.getProxyInstance(new SubjectImpl());
        subject.show();
    }

    /**
     * cglib动态代理
     */
    @Test
    public void proxy3() {
        /**
         * 不能用内部类的方式 否则一直会报错
         */
        CglibProxy proxy = new CglibProxy();
        SubjectImpl subject = (SubjectImpl) proxy.getProxyInstance(new SubjectImpl());
        subject.show();
    }


    /**
     * 获取Class对象的三种方式
     *
     * @throws Exception
     */
    @Test
    public void reflect() throws Exception {
        Class clazz1 = Class.forName("com.wei.code.proxy.DynamicProxy.InvokeHandler");
        Class clazz2 = SubjectImpl.class;
        Class clazz3 = new SubjectImpl().getClass();
    }


}
